var currentPage = 0;
var totalPages = 0;

var sendReportParams = function(params)  {
	var sUrl = "/simbel/reports/viewreport.submitLink?args=";
	
	for(i = 0 ; i < params.length ; i++) {
		sUrl+=params[i].id + "||" + params[i].value + "@@";
	}
	sUrl = sUrl.substring(0,sUrl.length - 2) ;
	
	var callback =
	{
	  success: sendReportParamsCallback,
	  failure: reportError,
	  timeout: 60000
	}	
	
	var table = document.getElementById("results-table-sorter");	
	if(table != null) {
		table.parentNode.removeChild(table);	
	}
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
	showLoading(true,"Executing Report");
}

var requestLazzyLoad = function(params)  {
	var sUrl = "/simbel/reports/viewreport.submitLink?args=";
	
	for(i = 0 ; i < params.length ; i++) {
		sUrl+=params[i].id + "||" + params[i].value + "@@";
	}
	
	currentPage++;
	
	sUrl = sUrl.substring(0,sUrl.length - 2) + "&currentPage=" + (currentPage);
	
	var callback =
	{
	  success: requestLazzyLoadCallback,
	  failure: reportError,
	  timeout: 60000
	}	
	
	var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null); 
	showAlert("Loading page " + currentPage, false);
}

var requestLazzyLoadCallback = function(o) {
	var xml = o.responseXML;
	
	totalRows = jQuery(xml).find("detail").attr('rows');
	totalPages = jQuery(xml).find("detail").attr('totalPages');
	currentPage = jQuery(xml).find("detail").attr('currentPage');
	
	var tbody = document.getElementById("tbody-results-table");
	jQuery(xml).find("row").each(function() {
        var row = jQuery(this);
        tr = document.createElement("tr");
        tr.setAttribute("display", "none");
        
        jQuery(row).find("column").each(function() {
        	var column = jQuery(this);
        	td = document.createElement("td");
        	content = document.createTextNode(column.attr('value'))
        	
        	td.appendChild(content);
        	tr.appendChild(td);
        	
        	tbody.appendChild(tr);
        	
        });
	});
	
  	jQuery("#results-table-sorter").trigger("update");
	
	if(parseInt(currentPage) < parseInt(totalPages)) {
		requestLazzyLoad(recollectReportParams());
	} else {
		showAlert("Report loaded [ " + totalRows + " rows ]", false);
	  	var sorting = [[1,0]];
		jQuery("#results-table-sorter").trigger("sorton",[sorting]).tablesorterPager({container: jQuery("#pager"), size: 10});
	}
	
}

var recollectReportParams = function() {
	var params = new Array();	
  	jQuery("input[type='text']").each(function() {
      	var id = jQuery(this).attr("id");
      	var style = jQuery(this).attr("class");
      	var value =  jQuery(this).attr("value");

      	if(id != "pageNumber" && id != "pagedisplay") {
	      	if(style == "datepicker") {
				value = $.datepicker.formatDate('yyyy-mm-dd', value);
	      	}
	      	paramReport = new Object();
	      	paramReport.id = id;
			paramReport.value = value;
			params[params.length] = paramReport;
      	}
	});
  	
  	return params;
}

var openReport = function(url, params) {
	url += "?args=";
	for(i = 0 ; i < params.length ; i++) {
		url+=params[i].id + "||" + params[i].value + "@@";
	}
	url = url.substring(0,url.length - 2)
	openNewWindow(url);	
}

var reportError = function() {
	showLoading(false,"");
}

var openNewWindow = function(url) {
	window.open (url,"mywindow","menubar=1,resizable=1,width=350,height=250"); 	
}

var sendReportParamsCallback = function(o) {
	var xml = o.responseXML;
	var table =  document.createElement('table');
	var thead = document.createElement('thead');
	var tbody = document.createElement('tbody');
	
	tbody.setAttribute("id", "tbody-results-table");
	
	table.appendChild(thead);

	table.setAttribute("class", "tablesorter");
	table.setAttribute("id", "results-table-sorter");
	
	elementToRemove = document.getElementById("results-table");
	if(elementToRemove != null) {
		document.getElementById('resultsTable').removeChild(elementToRemove);
	}
	
	error = jQuery(xml).find("detail").attr('error');
	if(error != "") {
		showLoading(false,"");
		showAlert("Error : " + error, false);
		return;
	}
	
	totalRows = jQuery(xml).find("detail").attr('rows');
	totalPages = jQuery(xml).find("detail").attr('totalPages');
	currentPage = jQuery(xml).find("detail").attr('currentPage');
	
	jQuery("#resultsTable").css("display","block");

    tr = document.createElement("tr");
    //tr.setAttribute("class", "results-table-tr-header");
	jQuery(xml).find("header-label").each(function() {
        var label = jQuery(this);
        td = document.createElement("th");
        content = document.createTextNode(label.attr('value'))
        td.appendChild(content);
        tr.appendChild(td);
	});
	
	thead.appendChild(tr);
	table.appendChild(tbody);	
	jQuery(xml).find("row").each(function() {
        var row = jQuery(this);
        tr = document.createElement("tr");
        //tr.setAttribute("class", "results-table-tr-body");
        
        jQuery(row).find("column").each(function() {
        	var column = jQuery(this);
        	td = document.createElement("td");
        	content = document.createTextNode(column.attr('value'))
        	
        	td.appendChild(content);
        	tr.appendChild(td);
        	
        	tbody.appendChild(tr);
        	
        });
	});
	
	document.getElementById('resultsTable').appendChild(table);	
	jQuery("#results-table-sorter").tablesorter({
            widthFixed: true, 
            widgets: ['zebra']		
	}); 
	
	showLoading(false,"");

	if(currentPage < (totalPages - 1)) {
		requestLazzyLoad(recollectReportParams());
		showAlert("Report partially loaded. Getting all de rows [ " + totalRows + " ]", false);
	} else {
		showAlert("Report loaded  [ " + totalRows + " rows ]", false);	
	}
}

var showLoading = function(show, message) {
	YAHOO.namespace("example.container");
	if (!YAHOO.example.container.wait) {
		YAHOO.example.container.wait = 
			new YAHOO.widget.Panel("wait",  
					{ width:"240px", 
				fixedcenter:true, 
				close:false, 
				draggable:false, 
				zindex:4,
				modal:true,
				visible:false
					} 
			);
	}

	YAHOO.example.container.wait.setHeader("Loading, please wait...");
	YAHOO.example.container.wait.setBody('<img src="http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif" /><br />' + message);
	YAHOO.example.container.wait.render(document.body);
	if(show) {
		YAHOO.example.container.wait.show();
	} else {
		YAHOO.example.container.wait.hide();	
	}
}

var showAlert = function(_text, _stay) {
	jQuery.noticeAdd(
			{
				text : _text,
				stay: _stay
			}
	);
}